package com.zs.protocol;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class TCPProtocol implements Protocol{
	private ByteBuffer buffer;
	

	public TCPProtocol() {
		super();
		buffer=ByteBuffer.allocate(1024);
	}

	@Override
	public void handleAccept(SelectionKey key) throws IOException {
		ServerSocketChannel serverChannel=(ServerSocketChannel) key.channel();//之前创建此键的通道
		System.out.println("channel 2:"+serverChannel.hashCode());
		
		
		SocketChannel mChannel=serverChannel.accept();//创建于客户端的正式连接
		System.out.println("channel 3:"+mChannel.hashCode());
		mChannel.configureBlocking(false);
		mChannel.register(key.selector(), SelectionKey.OP_READ);
	}

	@Override
	public void handleRead(SelectionKey key) throws IOException {
		buffer.clear();
		SocketChannel clientChannel = (SocketChannel) key.channel();
		System.out.println("channel 4:"+clientChannel.hashCode());
		InetSocketAddress address=(InetSocketAddress) clientChannel.getRemoteAddress();
		int port=address.getPort();
		String host=address.getHostString();
		if(clientChannel.read(buffer)!=-1){
			buffer.flip();
			byte[] b=buffer.array();
			System.out.println("[HOST:"+host+",PORT:"+port+"]"+new String(b,0,b.length));
		}
		key.interestOps(SelectionKey.OP_WRITE);
	}

	@Override
	public void handleWrite(SelectionKey key) throws IOException {
		SocketChannel clientChannel = (SocketChannel) key.channel();
		System.out.println("channel 5:"+clientChannel.hashCode());
		
		
		clientChannel.write(ByteBuffer.wrap("hello client message1\r\n".getBytes()));
		clientChannel.write(ByteBuffer.wrap("hello client message2".getBytes()));
		clientChannel.close();
	}


}
